package com.retail.order.service.impl;

import com.retail.common.core.domain.Result;
import com.retail.order.domain.OrderSku;
import com.retail.order.domain.TOrder;
import com.retail.order.domain.TOrderDetails;
import com.retail.order.dto.OrderDetailResponse;
import com.retail.order.mapper.OrderDetailMapper;
import com.retail.order.service.OrderDetailService;
import com.retail.shopping.remote.ProductFeign;
import com.retail.shopping.remote.ShoppingCartFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 33253
 */
@Service
public class OrderDetailServiceImpl implements OrderDetailService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private ShoppingCartFeign shoppingCartFeign;

    @Override
    public List<OrderDetailResponse> lookDetail(Long orderId) {
        return orderDetailMapper.lookDetail(orderId);
    }

    @Override
    public Result orderDetailInstall(TOrderDetails tOrderDetails) {
        /*
        * 新增订单详情表
        * 增加完成后进行与其他服务的联动操作
        *   购物车清除
        *   商品数量扣除
        *   修改订单状态
        *   修改优惠卷数量
        * 还有就是这里有太多对数据库的操作了会影响性能后续会通过mq异步合并接口来操作数据库 qps
        * */
        //新增订单详情表
        Integer num = orderDetailMapper.orderDetailInstall(tOrderDetails);
        //判断是否添加成功
        if(num<=0){
            throw new RuntimeException ("订单记录表生成失败稍后会将付款金额推到您的账户");
        }
        //对商品表进行操作减去购买商品的数量
        List<OrderSku> orderSkus = orderDetailMapper.orderSkuList(tOrderDetails.getOrderId ());
        String str = "";
        String number = "";
        if(orderSkus.size ()!=0){
            for (OrderSku skus : orderSkus) {
                if(skus.getSkuId ()!=null && skus.getSkuNumber ()!=null){
                    str+=","+skus.getSkuId ();
                    number+=","+skus.getSkuNumber ();
                }
            }
            if(!number.isEmpty () &&  !str.isEmpty ()){
                number = number.substring(1);
                str = str.substring(1);
                System.out.println (number);
                System.out.println (str);
                productFeign.orderSkuUpdNumber(str,number);
            }
        }
        //更改生成订单的状态改为已支付
        orderDetailMapper.orderUpdStatus(tOrderDetails.getOrderId ());
        //删除购物车中的数据
        TOrder tOrder = orderDetailMapper.orderGetUserId(tOrderDetails.getOrderId ());
        //删除数据库总的购物车数据
        shoppingCartFeign.deleteCartMiddenBySkuUser(tOrder.getUserId (),str);
        return Result.success ("","商品购买成功");
    }
}
